// OTA升级检查功能实现
document.addEventListener('DOMContentLoaded', function() {
  const checkUpdateBtn = document.getElementById('checkUpdateBtn');
  const startUpdateBtn = document.getElementById('startUpdateBtn');
  const otaSteps = document.querySelectorAll('.ota-step');
  const updateProgressBar = document.getElementById('updateProgressBar');
  const updateProgressText = document.getElementById('updateProgressText');
  const updateResult = document.getElementById('updateResult');
  const resultIcon = document.getElementById('resultIcon');
  const resultTitle = document.getElementById('resultTitle');
  const resultDescription = document.getElementById('resultDescription');
  const latestVersionEl = document.querySelector('#latestVersion p');
  const updateIndicator = document.getElementById('updateIndicator');
  // 模拟有新版本可用
  let hasNewVersion = false;
  const newVersion = "v2.4.0";
  // 检查更新按钮点击事件
  if (checkUpdateBtn) {
    checkUpdateBtn.addEventListener('click', checkForUpdates);
  }
  // 开始升级按钮点击事件
  if (startUpdateBtn) {
    startUpdateBtn.addEventListener('click', startOTAUpdate);
  }
  // 检查更新
  function checkForUpdates() {
    // 重置状态
    resetUpdateState();
    
    // 禁用检查按钮，显示加载状态
    checkUpdateBtn.disabled = true;
    checkUpdateBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 检查中...';
    checkUpdateBtn.classList.add('bg-gray-400');
    checkUpdateBtn.classList.remove('bg-primary', 'hover:bg-primary/90');
    
    // 更新最新版本显示
    latestVersionEl.textContent = '检查中...';
    
    // 模拟检查过程
    setTimeout(() => {
      if (hasNewVersion) {
        // 有新版本
        latestVersionEl.textContent = newVersion;
        latestVersionEl.classList.add('text-success');
        
        // 显示更新指示器和升级按钮
        updateIndicator.classList.remove('hidden');
        startUpdateBtn.classList.remove('hidden');
        
        // 更新结果提示
        showUpdateResult('info', '发现新版本', `检测到最新版本 ${newVersion}，建议立即升级`);
      } else {
          isReallyOnline().then(isOnline => {
            console.log(`真实网络状态：${isOnline ? '联网' : '断网'}`);
            latestVersionEl.textContent = '当前已是最新版本';
            // 隐藏升级按钮
            startUpdateBtn.classList.add('hidden');
            // 更新结果提示
            showUpdateResult('success', '已是最新版本', '您的系统当前已是最新版本，无需升级');
          });
          // 无新版本
          latestVersionEl.textContent = '未连接到网络';
          // 隐藏升级按钮
          startUpdateBtn.classList.add('hidden');
          // 更新结果提示
          showUpdateResult('success', '未连接到网络', ' ');
      }
      
      // 恢复按钮状态
      checkUpdateBtn.disabled = false;
      checkUpdateBtn.innerHTML = '<i class="fa fa-refresh mr-1"></i> 检查更新';
      checkUpdateBtn.classList.remove('bg-gray-400');
      checkUpdateBtn.classList.add('bg-primary', 'hover:bg-primary/90');
    }, 2000); // 模拟2秒检查时间
  }
  
  async function isReallyOnline() {
    try {
      // 请求一个极小的公共资源（无跨域问题）
      const response = await fetch('https://www.baidu.com/favicon.ico', {
        method: 'HEAD', // 仅请求响应头，减少流量
        mode: 'cors',
        cache: 'no-cache' // 避免缓存影响结果
      });
      // 状态码 200-299 表示请求成功（即真实联网）
      return response.ok;
    } catch (error) {
      // 捕获网络错误（断网、跨域失败等）
      return false;
    }
  }


  // 开始OTA升级
  function startOTAUpdate() {
    // 重置状态
    resetUpdateState();
    
    // 禁用按钮
    checkUpdateBtn.disabled = true;
    startUpdateBtn.disabled = true;
    startUpdateBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 升级中...';
    startUpdateBtn.classList.remove('hover:bg-success/90');
    
    // 隐藏结果提示
    updateResult.classList.add('hidden');
    
    // 升级步骤和进度配置
    const stepsConfig = [
      { step: 'checking', duration: 2000, status: 'completed', message: '更新包检查完成' },
      { step: 'downloading', duration: 4000, status: 'completed', message: '更新包下载完成' },
      { step: 'verifying', duration: 3000, status: 'completed', message: '更新包验证通过' },
      { step: 'installing', duration: 5000, status: 'completed', message: '更新安装完成' },
      { step: 'rebooting', duration: 3000, status: 'completed', message: '系统重启完成' }
    ];
    
    // 逐个执行升级步骤
    let delay = 0;
    const totalSteps = stepsConfig.length;
    
    stepsConfig.forEach((config, index) => {
      delay += config.duration;
      
      setTimeout(() => {
        // 处理当前步骤
        const stepElement = document.querySelector(`[data-step="${config.step}"]`);
        const statusElement = stepElement.querySelector('.step-status');
        const iconElement = stepElement.querySelector('.step-icon');
        
        // 移除所有步骤的激活状态
        otaSteps.forEach(step => step.classList.remove('step-active'));
        
        // 标记当前步骤为激活
        stepElement.classList.add('step-active');
        
        // 更新状态文本和图标（显示加载中动画）
        statusElement.textContent = '处理中...';
        iconElement.innerHTML = '<div class="relative w-5 h-5"><div class="pulse-ring"></div><div class="pulse-dot"></div></div>';
        iconElement.classList.remove('bg-gray-100', 'bg-success/10', 'bg-danger/10');
        iconElement.classList.add('bg-primary/10');
        
        // 模拟步骤处理时间
        setTimeout(() => {
          // 更新步骤状态
          stepElement.classList.remove('step-active');
          stepElement.classList.add(`step-${config.status}`);
          
          // 更新图标和状态文本
          if (config.status === 'completed') {
            iconElement.innerHTML = '<i class="fa fa-check text-success"></i>';
            iconElement.classList.remove('bg-primary/10');
            iconElement.classList.add('bg-success/10');
            statusElement.textContent = config.message;
            statusElement.classList.add('text-success');
          } else {
            iconElement.innerHTML = '<i class="fa fa-times text-danger"></i>';
            iconElement.classList.remove('bg-primary/10');
            iconElement.classList.add('bg-danger/10');
            statusElement.textContent = '处理失败';
            statusElement.classList.add('text-danger');
          }
          
          // 更新进度
          const progress = Math.round(((index + 1) / totalSteps) * 100);
          updateProgressBar.style.width = `${progress}%`;
          updateProgressText.textContent = `${progress}%`;
          
          // 所有步骤完成
          if (index === totalSteps - 1) {
            setTimeout(() => {
              // 更新版本信息
              document.querySelector('#latestVersion p').textContent = newVersion;
              document.querySelector('#latestVersion p').classList.add('text-success');
              document.querySelector('.font-medium.mt-1').textContent = newVersion;
              
              // 隐藏更新指示器
              updateIndicator.classList.add('hidden');
              
              // 显示完成结果
              showUpdateResult('success', '系统升级完成', `系统已成功升级至 ${newVersion}，所有功能正常`);
              
              // 恢复按钮状态
              checkUpdateBtn.disabled = false;
              startUpdateBtn.disabled = false;
              startUpdateBtn.innerHTML = '<i class="fa fa-download mr-1"></i> 开始升级';
              startUpdateBtn.classList.add('hover:bg-success/90');
              startUpdateBtn.classList.add('hidden');
              
              // 更新状态为无新版本
              hasNewVersion = false;
            }, 1000);
          }
        }, config.duration - 500); // 减去前面的延迟
      }, index === 0 ? 500 : delay - 500);
    });
  }
  
  // 重置更新状态
  function resetUpdateState() {
    otaSteps.forEach(step => {
      step.classList.remove('step-active', 'step-completed', 'step-failed');
      const statusElement = step.querySelector('.step-status');
      const iconElement = step.querySelector('.step-icon');
      
      // 重置状态文本
      const stepName = step.dataset.step;
      const statusTexts = {
        checking: '等待检查',
        downloading: '等待下载',
        verifying: '等待验证',
        installing: '等待安装',
        rebooting: '等待重启'
      };
      
      statusElement.textContent = statusTexts[stepName];
      statusElement.classList.remove('text-success', 'text-danger');
      
      // 重置图标
      const iconClasses = {
        checking: 'fa-search',
        downloading: 'fa-download',
        verifying: 'fa-shield',
        installing: 'fa-cogs',
        rebooting: 'fa-refresh'
      };
      
      iconElement.innerHTML = `<i class="fa ${iconClasses[stepName]} text-gray-500"></i>`;
      iconElement.classList.remove('bg-primary/10', 'bg-success/10', 'bg-danger/10');
      iconElement.classList.add('bg-gray-100');
    });
    
    // 重置进度条
    updateProgressBar.style.width = '0%';
    updateProgressText.textContent = '0%';
    
    // 隐藏结果提示
    updateResult.classList.add('hidden');
    
    // 重置版本显示样式
    latestVersionEl.classList.remove('text-success');
  }
  
  // 显示更新结果
  function showUpdateResult(type, title, description) {
    // 设置结果样式和内容
    if (type === 'success') {
      resultIcon.className = 'w-8 h-8 rounded-full flex items-center justify-center mr-3 bg-success/10';
      resultIcon.innerHTML = '<i class="fa fa-check text-success"></i>';
      resultTitle.textContent = title;
      resultTitle.className = 'font-medium text-success';
    } else if (type === 'error') {
      resultIcon.className = 'w-8 h-8 rounded-full flex items-center justify-center mr-3 bg-danger/10';
      resultIcon.innerHTML = '<i class="fa fa-exclamation-triangle text-danger"></i>';
      resultTitle.textContent = title;
      resultTitle.className = 'font-medium text-danger';
    } else {
      resultIcon.className = 'w-8 h-8 rounded-full flex items-center justify-center mr-3 bg-primary/10';
      resultIcon.innerHTML = '<i class="fa fa-info text-primary"></i>';
      resultTitle.textContent = title;
      resultTitle.className = 'font-medium text-primary';
    }
    
    resultDescription.textContent = description;
    updateResult.classList.remove('hidden');
  }
});